package com.dayuanit.dy17.mix.zookeeper;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;

import java.util.List;

public class TestZk {

    private static final String zkServerHost = "192.168.2.139:2181";
    private static final int sessionTimeOut = 30 * 1000;
    private static final int connectionTimeOut = 30 * 1000;

    public static void main(String[] args) throws Exception {

        //重试策略 最多重试三次，每次间隔1秒钟
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
        CuratorFramework client = CuratorFrameworkFactory.newClient(zkServerHost, sessionTimeOut, connectionTimeOut, retryPolicy);

        //发起和zk服务器连接请求
        client.start();

        //操作Zookeeper CRUD  增删改查

        //创建持久型节点
//        client.create().forPath("/java-test", "this is java test zk".getBytes());
//        client.create().forPath("/java-tmp", "this is java test zk".getBytes());

        //创建持久顺序型节点
//        client.create().withMode(CreateMode.PERSISTENT_SEQUENTIAL).forPath("/java-test/t");

        //创建临时节点
//        client.create().withMode(CreateMode.EPHEMERAL).forPath("/java-test-temp");

        //创建临时顺序节点
//        client.create().withMode(CreateMode.EPHEMERAL_SEQUENTIAL).forPath("/java-tmp/t");

        //查询节点
//        byte[] bytes = client.getData().forPath("/java-test");
//        System.out.println(new String(bytes));

        //查询子节点
//        List<String> strings = client.getChildren().forPath("/java-test");
//        for (String nodeName : strings) {
//            System.out.println(nodeName);
//            byte[] bytes = client.getData().forPath("/java-test/" + nodeName);
//            System.out.println(new String(bytes));
//        }

        //创建多层级节点 /a/b/c
        client.create()
                .creatingParentContainersIfNeeded()
                .withMode(CreateMode.PERSISTENT)
                .forPath("/a/b/c");

    }
}
